import axios from 'axios'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import {
    json2Str
} from './common/common'
import defaultConf from '../env'

// 请求次数
let requestCount = 0;

class Request {
    constructor() {
        console.log(defaultConf);
        console.log(`defaultConf`, defaultConf.targetUrl);
        // this.baseUrl = 'http://localhost:4001';
        this.baseURL = defaultConf.targetUrl;
        this.timeout = 500;

        this._axios = axios.create({
            baseURL: this.baseURL,
        })
        this.commomParams = {
            time: +new Date(),
        } // 状态码错误信息
        // eslint-disable-next-line no-undef
        this.codeMessages = new Map([
            [200, ['服务器成功返回请求的数据。']],
            [201, ['新建或修改数据成功。']],
            [202, ['一个请求已经进入后台排队（异步任务）。']],
            [204, ['删除数据成功。']],
            [400, ['发出的请求有错误，服务器没有进行新建或修改数据的操作。']],
            [401, ['用户没有权限（令牌、用户名、密码错误）。', '/Login']],
            [403, ['用户得到授权，但是访问是被禁止的。', '/Login']],
            [404, ['发出的请求针对的是不存在的记录，服务器没有进行操作。']],
            [406, ['请求的格式不可得。']],
            [410, ['请求的资源被永久删除，且不会再得到的。']],
            [422, ['当创建一个对象时，发生一个验证错误。']],
            [500, ['服务器发生错误，请检查服务器。']],
            [502, ['网关错误。']],
            [503, ['服务不可用，服务器暂时过载或维护。']],
            [504, ['网关超时。']],
            ['default', ['请联系管理员']],
        ]);

        this._axios.interceptors.request.use(
            request => {
                if (requestCount == 0){
                    Nprogress.start();
                }
                requestCount++
                return request;
            },
            err => {
                Nprogress.done();
                requestCount = 0;
                return new Promise((res, rej) => {
                    alert('网络错误')
                    rej(err)
                })
            }
        )
        this._axios.interceptors.response.use(
            response => {
                Nprogress.done();
                requestCount--
                const {
                    code,
                    msg,
                    data,
                } = response.data || {};

                // code值是和后端 约定 
                // promise reject
                const status = (code === 0 || code === 200) ? 0 : 1;
                return new Promise((res, rej) => {
                    if (status === 1) {
                        alert(msg);
                        rej(msg)
                    } else {
                        res({
                            status: (code === 0 || code === 200) ? 0 : 1,
                            msg,
                            data,
                        })
                    }
                })
            },
            err => {
                Nprogress.done();
                requestCount = 0;
                return new Promise((res, rej) => {
                    alert('网络错误')
                    rej(err)
                })
            }
        )
    }

    // response
    
    // 公共参数处理
    http = (url, data, type = 'get') => {
        let newUrl = url;
        const newData = json2Str(data);
        const commonParams = json2Str(this.commomParams);
        if (newData) {
            newUrl = `${url}?${newData}&${commonParams}`;
        }

        if (type != 'get') {
            return Object.assign({}, this.commomParams, data)
        }
        return newUrl;
    }

    get = (url, data) => {
        const newUrl = this.http(url, data);
        return this._axios.get(newUrl);

    }
    post = (url, data) => {
        const newParams = this.http(url, data, 'post');
        return this._axios.post(url, newParams);
    }

    // put delete

}

export default new Request();